package com.linux.huhx.business.action;

import com.alibaba.fastjson.JSONObject;
import com.linux.huhx.base.BaseController;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by huhx on 2017-07-14.
 */
public class OkHttpQrCode extends BaseController {


    @Override
    protected Map handleInner(HttpServletRequest requests, HttpServletResponse responses) throws Exception {
        Map map = new HashMap();
        String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=tEjwxidPAl-D0tcZxVD_TUdpKIT24VnuirDIwfCdFhVDL9-P5brgKFI7TExOINFhLWoyDFjrSSJvlEa0H6YBIEEX4ujPpqr7_eVTXY3JXCT1CZNpkNpBQIioEGR94m3mLKVaAIAZYJ";
        MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        JSONObject json = new JSONObject();
        json.put("path", requests.getAttribute("path"));
        json.put("width", requests.getAttribute("width"));
//        json.put("path", "path/huhx.jpg");
//        json.put("width", 430);
        RequestBody requestBody = RequestBody.create(JSON_TYPE, json.toJSONString());
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            ResponseBody body = response.body();
            byte[] bytes = body.bytes();
//            IOUtils.write(bytes, new FileOutputStream("G:\\Java\\WeiXin\\2017-08-02\\HuhxLean2\\pages\\images/liuling.jpg"));
//            map.put("impath", "/pages/images/liuling.jpg");
            String string = Base64.encodeBase64String(bytes);
//            System.out.println(string);
            map.put("string", "data:image/jpeg;base64," + string);
            body.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        File file = new File("D:/liuling.png");
//        InputStream stream = new FileInputStream(file);
//        byte[] bytes = new byte[stream.available()];
//        System.out.println(Base64.isBase64(bytes));
//
//        stream.read(bytes);
//        stream.close();
//        String string = Base64.encodeBase64String(bytes);
//        String str = new String(bytes);
//
//        map.put("str", str);
//        map.put("byte", bytes);
//        map.put("string", string);
//        System.out.println(str);
        return map;
    }

    public static void main(String[] args) throws Exception{
        new OkHttpQrCode().handleInner(null, null);
    }
}